package http_server

import (
	"html/template"
	"log"
	"net/http"
	"strings"
)

type HandlerFunc func(ctx *Context)
type Engine struct {
	*RouterGroup
	router        *router
	groups        []*RouterGroup
	htmlTemplates *template.Template // 模板集合
	funcMap       template.FuncMap   // 自定义模板函数
}

// New 创建服务器实例
func New() *Engine {
	engine := &Engine{router: newRouter()}
	engine.RouterGroup = &RouterGroup{engine: engine}
	engine.groups = []*RouterGroup{engine.RouterGroup}
	return engine

}

// addRoute 向路由表中添加一条路由规则
//
// 参数：
//   - method: HTTP请求方法（.如"GET", "POST"等）
//   - pattern: URL路径模式
//   - handler: 处理函数
func (engine *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
	engine.router.addRoute(method, pattern, handler)
}

// Run 启动服务器
func (engine *Engine) Run(addr string) error {
	log.Printf("Server is running on %s\n", addr)

	return http.ListenAndServe(addr, engine)
}

func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
	group.middlewares = append(group.middlewares, middlewares...)
}

// ServeHTTP 符合http.Handler接口的方法
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var middlewares []HandlerFunc
	for _, group := range engine.groups {
		if strings.HasPrefix(r.URL.Path, group.prefix) {
			middlewares = append(middlewares, group.middlewares...)
		}
	}
	ctx := NewContext(w, r)

	ctx.handlers = middlewares
	ctx.engine = engine // 传入engine实例，方便后续调用engine的方法

	engine.router.handle(ctx)
}
